const { tips, coludRequest,confirm } = require("../../util/util");
//获取应用实例
const app=new getApp()

Page({
  data:{
    openId:"",
    Addresslist:[]
  },
  onLoad:function (){
    var that=this
    //获取用户所有地址
    this.getAddress();
      this.setData({
        slideButtons: [{
          text: '编辑'
        },{
          type: 'warn',
          text: '删除',
          extClass: 'test'
        }],
    });
  },
  //滑动
  slideButtonTap(e){
    var that=this
    // 判断index编辑0 还是删除1
    if(e.detail.index==0){
      //编辑
      that.edit(e.target.dataset.id);
    }else{
      //删除
      let index=e.target.dataset.index;
      let id=e.target.dataset.id;
      that.delete(index,id);
    }
  },
  //根据openid查询用户数据
  getAddress:function(){
    var that=this;
    //获取openid，根据openid获取地址数据
    wx.cloud.callFunction({
      name:'login',
      data:{},
      success:res=>{
        let openId=res.result.userInfo.openId;
        coludRequest('admin',{module:'UserAddress',action:'query',map:{openId:openId}},function(res)
        {
            var arr=res.result.data;
            that.setData({Addresslist:arr})
        })
      },  
      fail:err=>{
        tips('发生了错误')
      }
    })
    

  },
  //添加地址
  addAddress:function(){
     wx.navigateTo({
       url: '/pages/my/address/addressAdd/aindex',
     }) 
  },
  //返回个人中心
  Fanmy:function(){
    wx.reLaunch({
      url: '/pages/my/mindex',
    })
  },
  //修改地址
  edit:function(data_id){
    let id=data_id;
    console.log(123);
    //传入id 并跳转页面
    wx.navigateTo({
      url: '/pages/my/address/addressAdd/aindex?id='+id,
    })
    
  },
  //删除数据
  delete:function(index,id){
    var that=this;
    confirm('确认删除该地址?',function(res){
      if(res.confirm){
        coludRequest('admin',{module:'UserAddress',action:'delete',map:{_id:id}},function(res){
          tips('删除成功',1200,'success')
          setTimeout((res) => {
            //获取之前的集合
            var list=that.data.Addresslist;
            //删除位置的结构
            list.splice(index,1);
            //给集合重新赋值
            that.setData({Addresslist:list})
          }, 1200);
        })
      }
    })
  }
})